// -----------------------------------------------------------------------
//  <copyright file="IntegrationEventHandlerBase.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-10-25 20:31</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Properties;


namespace DaprPlus.MediatR;

/// <summary>
/// 领域事件处理器基类
/// </summary>
/// <typeparam name="TDomainEvent">领域事件类型</typeparam>
public abstract class DomainEventHandlerBase<TDomainEvent> : INotificationHandler<DomainEventWrap<TDomainEvent>>
    where TDomainEvent : DomainEvent
{
    protected DomainEventHandlerBase(IServiceProvider provider)
    {
        Logger = provider.GetLogger(GetType());
    }

    /// <summary>
    /// 日志对象
    /// </summary>
    protected ILogger Logger { get; }

    /// <summary>
    /// 重写以实现领域事件处理逻辑
    /// </summary>
    /// <param name="event">领域事件</param>
    /// <param name="token"></param>
    /// <returns></returns>
    protected abstract Task OnHandle(TDomainEvent @event, CancellationToken token);

    /// <summary>
    /// 执行事件
    /// </summary>
    /// <param name="notification">领域事件MediatR-INotification包装</param>
    /// <param name="token"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public Task Handle(DomainEventWrap<TDomainEvent> notification, CancellationToken token = default)
    {
        var domainEvent = notification.DomainEvent;
        var source = domainEvent.EventSource.IsNullOrEmpty() ? "" : $"from {domainEvent.EventSource}";
        Logger.LogInformation(ResDaprPlus.Format_MediatR_EventHandler_Handing, GetType().FullName, source, domainEvent.GetType().FullName);
        return OnHandle(domainEvent, token);
    }
}
